package vn.edu.hut.soict.translate.transform;

import simplenlg.framework.LexicalCategory;
import vn.edu.hut.soict.lienkate.disjunct.Disjunct;
import vn.edu.hut.soict.translate.transform.utils.GrammaticalNumber;
import vn.edu.hut.soict.translate.transform.utils.VerbTransformUtils;
import vn.edu.hut.soict.translate.transform.utils.WordTransformUtils;

public class SubstitutionTransformer extends Transformer {

	public SubstitutionTransformer(InnerTransformer transformer) {
		super(transformer);
	}

	/*
	 * Substitute a token in destination token list with new (destination) word.
	 * @param i the position of the token
	 * @param newWord the word to substitute
	 */
	public void substitute(int i, String newWord) {
		String oldWord = destinationTokenList.get(i);
		String categoryString = null;
		if (destinationLinkage != null) {
			categoryString = destinationLinkage.getDisjuncts().get(i).getCategory();
		}
		LexicalCategory category = null;
		if (categoryString == null || categoryString.isEmpty()) {
			category = WordTransformUtils.lexicalCategory(oldWord);
		}

		if ((categoryString != null && categoryString.equals("n")) || category == LexicalCategory.NOUN) {
			newWord = GrammaticalNumber.nounDecline(newWord, GrammaticalNumber.nounOrPronounNumber(oldWord));
			destinationTokenList.set(i, newWord);
		}
		else if ((categoryString != null && categoryString.equals("v")) || category == LexicalCategory.VERB) {
			newWord = VerbTransformUtils.conjugateAs(newWord, oldWord);
			destinationTokenList.set(i, newWord);
			if (destinationLinkage == null) {
				destinationTokenList.set(i, newWord);
				return;
			}
			transformRecursively(i);
		}
		else {
			destinationTokenList.set(i, newWord);
			if (destinationLinkage == null) {
				destinationTokenList.set(i, newWord);
				return;
			}
			transformRecursively(i);
		}
	}

	public void fixDeterminer() {
		for (int i = 0; i < destinationLinkage.getDisjuncts().size(); i++) {
			Disjunct disjunct = destinationLinkage.getDisjuncts().get(i);
			if (disjunct.getCategory().equals("n")) {
				if (findRightConnection(destinationLinkage, i, "D", null) > 0) {
					String word = destinationTokenList.get(i);
					if (WordTransformUtils.startsWithAVowel(word)) {
						destinationTokenList.set(i, "an " + word);
					}
					else {
						destinationTokenList.set(i, "a " + word);
					}
				}
			}
		}
	}

}
